package logic

import (
	"community/models/cache"
	"community/models/mysql"
	"context"
	"encoding/json"
	"fmt"
	"time"

	"community/comrpc/comrpc"
	"community/comrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ComListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewComListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ComListLogic {
	return &ComListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ComListLogic) ComList(in *comrpc.ComListRequest) (*comrpc.ComListResponse, error) {
	// todo: add your logic here and delete this line
	var a []mysql.Home
	key := fmt.Sprintf("list")
	get, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if get != "" {
		json.Unmarshal([]byte(get), &a)
	} else {
		mysql.DB.Debug().Find(&a)
		jsonData, _ := json.Marshal(&a)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Hour*1)
	}
	var b []*comrpc.ComList
	for _, c := range a {
		list := comrpc.ComList{
			Name:    c.Name,
			Price:   float32(c.Price),
			Address: c.Address,
		}
		b = append(b, &list)
	}
	return &comrpc.ComListResponse{
		List: b,
	}, nil
}
